﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Web;
using System.Security.Principal;
using SAIM.Models.BLL;

namespace SAIM.Models
{
    public class SAIMIdentity : IIdentity
    {
        private IIdentity Identity { get; set; }
        private IEnumerable<Claim> Claims { get; set; }

        public string AuthenticationType
        {
            get
            {
                return Identity.AuthenticationType;
            }
        }

        public bool IsAuthenticated
        {
            get
            {
                return Identity.IsAuthenticated;
            }
        }

        public string Name
        {
            get
            {
                return Identity.Name;
            }
        }

        public SAIMIdentity(IIdentity identity)
        {
            Identity = identity;
            Claims = ((ClaimsIdentity)Identity).Claims;
        }

        public string GetUserName()
        {
            Claim ret = Claims.FirstOrDefault(c => c.Type.Contains("name"));

            return ret != null ? ret.Value : string.Empty;
        }

        public string GetUserId()
        {
            Claim ret = Claims.FirstOrDefault(c => c.Type.Contains("upn"));

            return ret != null ? ret.Value : string.Empty;
        }

        public string GetUserEmail()
        {
            Claim ret = Claims.FirstOrDefault(c => c.Type.Contains("emailaddress"));

            return ret != null ? ret.Value : string.Empty;
        }

        public bool IsInRole(string roleName)
        {
            using (AspNetUsersBLL user = new AspNetUsersBLL(GetUserId()))
            {
                if (user.isInRole(roleName))
                    return true;
                else
                    return false;
            }
        }

        public void ValidatePermissions(string role)
        {
            using (AspNetUsersBLL user = new AspNetUsersBLL(GetUserId()))
            {
                if (!user.isInRole(role))
                {
                    throw new HttpException(403, "Acces Denied");
                }
            }
        }
    }
}